<template>
  <div class="row">
    <div v-for="column in columnList" :key="column._id" class="col-4 mb-4">
      <div class="card h-100 shadow-sm">
        <div class="card-body text-center">
          <img :src="column.avatar && column.avatar.fitUrl" :alt="column.title" class="rounded-circle border border-light my-3" >
          <h5 class="card-title">{{column.title}}</h5>
          <p class="card-text text-left">{{column.description}}</p>
          <router-link :to="`/column/${column._id}`" class="btn btn-outline-primary">进入专栏</router-link>
          <div @click="postText(column)" v-if="column.author == currentUser._id" class="btn btn-outline-primary" style="margin-left:20px;">编辑</div>
          <div @click="deletePost(column)" v-if="column.author == currentUser._id" class="btn btn-outline-primary" style="margin-left:20px;background-color:red;border:none;color:#fff;">删除</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">

import { defineComponent, PropType, computed, ref } from 'vue'
import { ColumnProps } from '../store'
import { addColumnAvatar } from '../helper'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import createMessage from './createMessage'
export default defineComponent({
  name: 'ColumnList',
  props: {
    list: {
      type: Array as PropType<ColumnProps[]>,
      required: true
    }
  },
  setup (props, context) {
    console.log(ref(1), 'ref1')
    const deleteId = ref(1)
    const router = useRouter()
    const store = useStore()
    const currentUser:any = computed(() => store.state.user).value
    console.log(context)
    const columnList = computed(() => {
      return props.list.map(column => {
        addColumnAvatar(column, 50, 50)
        return column
      })
    })
    const postText = (column:any) => {
      if (currentUser._id) {
        if (currentUser._id === column.author) {
          router.push(`/posts/${column._id}`)
        } else {
          createMessage('不是你的文章无法编辑', 'error', 2000)
        }
      } else {
        createMessage('请先登录后才可以编辑', 'error', 2000)
      }
    }
    const deletePost = (column:any) => {
      console.log(column, 'column')
      console.log(currentUser, 'column')
      if (currentUser._id) {
        if (currentUser._id === column.author) {
          store.dispatch('deletePost', column._id).then(data => {
            console.log(data, 'data')
            createMessage('删除成功 2秒后跳转首页', 'success', 2000)
            setTimeout(() => {
              router.push('/')
            }, 2000)
          }).catch(e => {
            console.log(e)
          })
        } else {
          createMessage('不是你的文章无法删除', 'error', 2000)
        }
      } else {
        createMessage('请先登录后才可以删除', 'error', 2000)
      }
    }
    return {
      columnList,
      deletePost,
      postText,
      currentUser
    }
  }
})
</script>
<style scoped>
.card-body img {
  width: 50px;
  height: 50px;
}
</style>
